package com.ztr.suanfa.des;

import java.security.Key;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;


public class DESUtils {
    /**
     * logger.
     */
    private static Logger logger = Logger.getLogger(DESUtils.class);

    /**
     * 数据编码.
     */
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * 算法编号.
     */
    public static final String DES_NAME = "DES";

    /**
     * CBC模式串.
     */
    public static final String DES_NAME_ECB = "DES/CBC/PKCS5Padding";

    /**
     * 初始向量.
     */
    public static final byte[] DES_KEY_IV = { 1, 2, 3, 4, 5, 6, 7, 8 };

    /**
     * 根据密码生成Key.要求：密码长度是8的倍数.
     * @param desKeyPwd 密码字符串.
     * @return DES密钥.
     * @throws Exception 可能异常.
     */
    public static String generateDesKey(String desKeyPwd) throws Exception {
        DESKeySpec desKeySpec = null;
        SecretKeyFactory keyFactory = null;
        byte[] keyBytes = null;

        desKeySpec = new DESKeySpec(desKeyPwd.getBytes(CHARSET_UTF8));
        keyFactory = SecretKeyFactory.getInstance(DES_NAME);
        keyBytes = keyFactory.generateSecret(desKeySpec).getEncoded();
        return Base64.encodeBase64String(keyBytes);
    }

    /**
     * 对文本内容进行加密.
     * @param plainText 待加密明文内容.
     * @param desKey DES密钥.
     * @return 加密的密文.
     */
    public static String encodeText(String plainText, String desKey) throws Exception {
        byte[] desKeyBytes = null;
        byte[] plainBytes = null;
        byte[] cipherBytes = null;

        try {
            desKeyBytes = Base64.decodeBase64(desKey);
            plainBytes = plainText.getBytes(CHARSET_UTF8);
            cipherBytes = encodeByCbc(plainBytes, desKeyBytes, DES_KEY_IV);
            return Base64.encodeBase64String(cipherBytes);
        } catch (Exception ex) {
            logger.error("DESUtil.encodeText.", ex);
            return "";
        }
    }

    /**
     * 对文本密文进行解密.
     * @param cipherText 待解密密文.
     * @param desKey DES密钥.
     * @return 解密的明文.
     */
    public static String decodeText(String cipherText, String desKey) throws Exception {
        byte[] desKeyBytes = null;
        byte[] cipherBytes = null;
        byte[] plainBytes = null;

        try {
            desKeyBytes = Base64.decodeBase64(desKey);
            cipherBytes = Base64.decodeBase64(cipherText);
            plainBytes = decodeByCbc(cipherBytes, desKeyBytes, DES_KEY_IV);
            return new String(plainBytes, CHARSET_UTF8);
        } catch (Exception ex) {
            logger.error("DESUtil.decodeText.", ex);
            return "";
        }
    }

    /**
     * 对字节数组内容进行加密.
     * @param plainBytes 待加密明文内容.
     * @param desKey DES密钥.
     * @return 加密的密文.
     */
    public static byte[] encodeBytes(byte[] plainBytes, String desKey) throws Exception {
        byte[] desKeyBytes = null;
        byte[] cipherBytes = null;

        try {
            desKeyBytes = Base64.decodeBase64(desKey);
            cipherBytes = encodeByCbc(plainBytes, desKeyBytes, DES_KEY_IV);
            return cipherBytes;
        } catch (Exception ex) {
            logger.error("DESUtil.encodeBytes.", ex);
            return new byte[0];
        }
    }

    /**
     * 对字节数组密文进行解密.
     * @param cipherBytes 待解密密文.
     * @param desKey DES密钥.
     * @return 解密的明文.
     */
    public static byte[] decodeBytes(byte[] cipherBytes, String desKey) throws Exception {
        byte[] desKeyBytes = null;
        byte[] plainBytes = null;

        try {
            desKeyBytes = Base64.decodeBase64(desKey);
            plainBytes = decodeByCbc(cipherBytes, desKeyBytes, DES_KEY_IV);
            return plainBytes;
        } catch (Exception ex) {
            logger.error("DESUtil.decodeBytes.", ex);
            return new byte[0];
        }
    }

    /**
     * DES算法使用CBC模式进行加密.
     * @param plainBytes 原文内容.
     * @param desKey DES密钥.
     * @param keyIv DES初始向量.
     * @return 加密后的内容.
     * @throws Exception .
     */
    public static byte[] encodeByCbc(byte[] plainBytes, byte[] desKey, byte[] keyIv) throws Exception {
        Key deskey = null;
        DESKeySpec desSpec = null;
        SecretKeyFactory keyFactory = null;
        Cipher cipher = null;
        IvParameterSpec ivSpec = null;
        byte[] cipherOut = null;

        desSpec = new DESKeySpec(desKey);
        keyFactory = SecretKeyFactory.getInstance(DES_NAME);
        deskey = keyFactory.generateSecret(desSpec);
        cipher = Cipher.getInstance(DES_NAME_ECB);
        ivSpec = new IvParameterSpec(keyIv);
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ivSpec);
        cipherOut = cipher.doFinal(plainBytes);
        return cipherOut;
    }

    /**
     * DES算法使用CBC模式进行解密.
     * @param plainBytes 密文内容.
     * @param desKey DES密钥.
     * @param keyIv DES初始向量.
     * @return 解密后的内容.
     * @throws Exception .
     */
    public static byte[] decodeByCbc(byte[] plainBytes, byte[] desKey, byte[] keyIv) throws Exception {
        Key deskey = null;
        DESKeySpec desSpec = null;
        SecretKeyFactory keyFactory = null;
        Cipher cipher = null;
        IvParameterSpec ivSpec = null;
        byte[] cipherOut = null;

        desSpec = new DESKeySpec(desKey);
        keyFactory = SecretKeyFactory.getInstance(DES_NAME);
        deskey = keyFactory.generateSecret(desSpec);
        cipher = Cipher.getInstance(DES_NAME_ECB);
        ivSpec = new IvParameterSpec(keyIv);
        cipher.init(Cipher.DECRYPT_MODE, deskey, ivSpec);
        cipherOut = cipher.doFinal(plainBytes);
        return cipherOut;
    }

    public static void main(String[] args) throws Exception {
        String desKeyPwd = "1234567887654321";
        String desKey = null;
        String plainText = "This is 一段明文内容！";
        String cipherText = null;

        System.out.println("----------------------- 获取DES秘钥 -------------------------");
        desKey = DESUtils.generateDesKey(desKeyPwd);
        System.out.println("秘钥：" + desKey);
        System.out.println();
        // 文本加解密测试.
        System.out.println("----------------------- 文本加解密测试 -------------------------");
        System.out.println("明文：" + plainText);
        cipherText = DESUtils.encodeText(plainText, desKey);
        System.out.println("密文：" + cipherText);
        plainText = DESUtils.decodeText(cipherText, desKey);
        System.out.println("解密明文：" + plainText);
        System.out.println();
        System.out.println("----------------------- 字节数组加解密测试 -------------------------");
        byte[] plainBytes = plainText.getBytes("UTF-8");
        byte[] cipherBytes = null;
        System.out.println("明文：" + Arrays.toString(plainBytes));
        cipherBytes = DESUtils.encodeBytes(plainBytes, desKey);
        System.out.println("密文：" + Arrays.toString(cipherBytes));
        plainBytes = DESUtils.decodeBytes(cipherBytes, desKey);
        System.out.println("解密明文：" + Arrays.toString(plainBytes));
        System.out.println();
    }
}
